package com.paireach.bw.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.baidu.trace.TraceLocation;
import com.blankj.utilcode.utils.NetworkUtils;
import com.paireach.bw.R;
import com.paireach.bw.activity.ExceQianShouActivity;
import com.paireach.bw.adapter.CommonUnloadAdapter;
import com.paireach.bw.application.MyApplication;
import com.paireach.bw.base.BaseFragment;
import com.paireach.bw.bean.DriveOrder;
import com.paireach.bw.bean.LocationInfo;
import com.paireach.bw.bean.OrderResult;
import com.paireach.bw.bean.OrdersBean;
import com.paireach.bw.bean.ReturnInfo;
import com.paireach.bw.event.AppEvent;
import com.paireach.bw.event.HttpErrorEvent;
import com.paireach.bw.event.HttpSuccessEvent;
import com.paireach.bw.http.RequestTag;
import com.paireach.bw.http.WayBillRequest;
import com.paireach.bw.interface2.LocateCallback;
import com.paireach.bw.utils.BDTraceUtil;
import com.paireach.bw.utils.GsonUtil;
import com.paireach.bw.utils.LogUtil;
import com.paireach.bw.view.CustomDividerItemDecoration;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

/**
 * Created by ${cqc} on 2017/6/20.
 */

public class CommonFrag240 extends BaseFragment {

    private List<OrdersBean> orderList;
    private String orderCode;

    private View rootView;
    private RecyclerView recyclerView;
    private Toolbar toolbar;

    public static CommonFrag240 getInstance(OrderResult orderResult) {
        CommonFrag240 frag = new CommonFrag240();
        Bundle bundle = new Bundle();
        bundle.putSerializable("KaOrderResult", orderResult);
        frag.setArguments(bundle);
        return frag;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        OrderResult orderResult = (OrderResult) bundle.getSerializable("KaOrderResult");
        orderList = orderResult.getOrders();
        orderCode = orderList.get(0).getORDER_CODE();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.activity_common_end_factory, container, false);
        findViews();
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initViews();
    }


    @Override
    public void httpSuccessEvent(HttpSuccessEvent event) {
        super.httpSuccessEvent(event);
        dismissProgressDialog();
        if (event.getRequestTag() == RequestTag.DRIVER_SIGN_ORDER || event.getRequestTag() == RequestTag.INTO_END_FACTORY
                || event.getRequestTag() == RequestTag.OUT_END_FACTORY) {
            ReturnInfo info = GsonUtil.jsonToBean(event.getJson(), ReturnInfo.class);
            showToast(info.getMsg());
            if (info.getStatus() == 1) {
                AppEvent appEvent = new AppEvent();
                appEvent.setTag("GetOrderCodeDetail");//通知CommonActivity页面请求数据，然后更新fragment
                EventBus.getDefault().post(appEvent);
            }
        }
    }

    @Override
    public void httpErrorEvent(HttpErrorEvent event) {
        super.httpErrorEvent(event);
        dismissProgressDialog();
        if (event.getRequestTag() == RequestTag.DRIVER_SIGN_ORDER || event.getRequestTag() == RequestTag.INTO_END_FACTORY
                || event.getRequestTag() == RequestTag.OUT_END_FACTORY) {
            showToast(event.getErrorMessage());
            AppEvent appEvent = new AppEvent();
            appEvent.setTag("加载失败");
            EventBus.getDefault().post(appEvent);
        }
    }


    private void initViews() {
        toolbar.setTitle("已到达送货地");
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().onBackPressed();
            }
        });

        //显示提提内容
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < orderList.size(); i++) {
            String shpm_status2 = orderList.get(i).getSHPM_STATUS();
            if ("241".equals(shpm_status2) || "242".equals(shpm_status2) || "245".equals(shpm_status2) || "248".equals(shpm_status2)) {
                sb.append(orderList.get(i).getSHPM_NUM() + ",");
            }
        }

        recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
//        recyclerView.addItemDecoration(new DividerItemDecoration(context, LinearLayoutManager.VERTICAL));
        recyclerView.addItemDecoration(new CustomDividerItemDecoration(context, CustomDividerItemDecoration.VERTICAL));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        CommonUnloadAdapter adapter = new CommonUnloadAdapter(orderList);
        recyclerView.setAdapter(adapter);

        View headView = LayoutInflater.from(context).inflate(R.layout.header_common_load, recyclerView, false);
        adapter.addHeaderView(headView);
        initHeadViews(headView);

        adapter.setOnItemClickListener(new CommonUnloadAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (NetworkUtils.isConnected()) {
                    if (position == 0) {//点击header，不作任何处理
                        return;
                    }
                    showProgressDialog();
                    String shpm_num = orderList.get(position - 1).getSHPM_NUM();//交货单号
                    String shpm_status = orderList.get(position - 1).getSHPM_STATUS();
                    LocationInfo location = ((MyApplication) getActivity().getApplication()).locationInfo;
                    LogUtil.d("position=" + position + ",shpm_num=" + shpm_num + ",shpm_status=" + shpm_status);
                    switch (view.getId()) {
                        case R.id.btn:
                            switch (shpm_status) {
                                case "230":
                                    new WayBillRequest().sign(phoneNumber, name,orderCode, shpm_num, "TO", location.getLongitude() + "", location.getLatitude() + "", driverNum);//收工厂签到
                                    break;
                                case "238":
                                    new WayBillRequest().intoEndFactory(phoneNumber, orderCode, shpm_num, "true", location.getLongitude() + "", location.getLatitude() + "", driverNum);
                                    break;
                                case "240":
                                    new WayBillRequest().outEndFactory(phoneNumber, orderCode, shpm_num, "true", location.getLongitude() + "", location.getLatitude() + "", driverNum);
                                    break;
                                case "241":
                                    showToast("你已经点击了入厂入厂拒绝，不可再次点击");
                                    break;
                            }
                            break;
                        case R.id.btn2:
                            Intent intent = new Intent(context, ExceQianShouActivity.class);
                            intent.putExtra("orderCode", orderCode);
                            intent.putExtra("shpmNum", shpm_num);
                            intent.putExtra("type", "262");//异常签收
                            startActivity(intent);
                            break;
                    }
                } else {
                    showToast("网络连接不可用，请稍后重试");
                }
            }
        });
    }

    private void initHeadViews(View headView) {
        TextView tv_tip = (TextView) headView.findViewById(R.id.tv_tip);
        TextView tv_order_num_parent = (TextView) headView.findViewById(R.id.tv_order_num_parent);
        TextView tv_origin_address_parent = (TextView) headView.findViewById(R.id.tv_origin_address_parent);
        TextView tv_weight = (TextView) headView.findViewById(R.id.tv_weight);
        TextView tv_contacts_parent = (TextView) headView.findViewById(R.id.tv_contacts_parent);
        TextView tv_contacts_tel_parent = (TextView) headView.findViewById(R.id.tv_contacts_tel_parent);

        tv_tip.setText(getResources().getString(R.string.common_tip_240));
        OrdersBean info = orderList.get(0);
        tv_order_num_parent.setText("负载单号：" + info.getORDER_CODE());
        tv_origin_address_parent.setText("发货地址：" + info.getFRM_SHPG_ADDR());
        tv_weight.setText("货物重量：" + info.getBW_WGT() + "kg");
        tv_contacts_parent.setText("联系人：" + info.getDRIVER_NAME());
        tv_contacts_tel_parent.setText("电话：" + info.getDRIVER_MOBILE());
    }

    private void findViews() {
        toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
    }
}
